/*
** decompose.c for minishell1 in /home/demesy_j/Projets/minishell1
** 
** Made by julien demesy
** Login   <demesy_j@epitech.net>
** 
** Started on  Mon Dec 12 14:41:07 2011 julien demesy
** Last update Tue Mar 13 18:53:45 2012 julien demesy
*/

#include	<stdlib.h>
#include	<string.h>

int		my_nbword(char *s)
{
  int		i;
  int		nbword;

  i = 0;
  nbword = 1;
  while (s[i])
    {
      if (s[i] == ' ')
	nbword++;
      i++;
    }
  return (nbword);
}

void		*xmalloc(int size)
{
  void		*ret;

  if ((ret = malloc(size)) == NULL)
    exit(EXIT_FAILURE);
  return (ret);
}

int		to_end(char *str, int pos)
{
  int		a;
  int		flag;

  a = 0;
  flag = 0;
  a = pos;
  while (str[a] != 0)
    {
      if (str[a] != ' ' && str[a] != '\t')
	flag = 1;
      a++;
    }
  return (flag);
}

char		*epur_str(char *str)
{
  int		a;
  int		b;
  int		count_space;
  int		letter;
  char		*res;

  if (str != 0)
    {
      res = xmalloc(sizeof(char *) * strlen(str));
      for (a = 0, b = 0, count_space = 0, letter = 0; str[a] != 0; a++)
	{
	  if (str[a] != ' ' && str[a] != '\t')
	    {
	      res[b++] = str[a];
	      count_space = 0;
	      letter++;
	    }
	  if ((str[a] == ' ' || str[a] == '\t') && letter != 0 && 
	      count_space == 0 && to_end(str, a) > 0)
	    {
	      count_space++;
	      res[b++] = str[a];
	    }
	}
      res[b] = 0;
      return (res);
    }
  return (0);
}

char		**alloc_tab(char *str)
{
  char		**tab;
  int		i;
  int		k;
  int		szw;

  tab = xmalloc(sizeof(*tab) * (my_nbword(str) + 1));
  i = 0;
  k = 0;
  while (str[i])
    {
      szw = 0;
      while (str[i] != ' ' && str[i])
        {
          szw++;
          i++;
        }
      if (szw)
        tab[k++] = xmalloc(sizeof(**tab) * (szw + 1));
      i++;
    }
  tab[k] = '\0';
  return (tab);
}

char		**decompose_simple(char *str)
{
  int		i;
  int		j;
  int		k;
  char		**tab;

  str = epur_str(str);
  tab = alloc_tab(str);
  i = 0;
  j = 0;
  while (str[i])
    {
      k = 0;
      while (str[i] != ' ' && str[i] && str[i] != '\n')
        tab[j][k++] = str[i++];
      if (k)
	tab[j++][k] = '\0';
      if (str[i])
        i++;
    }
  tab[j] = NULL;
  free(str);
  return (tab);
}
